import { defineStore } from 'pinia'
import type { ApiResponse } from '@/api/types'
import { registerApi } from '@/api/auth/register'
import { useUserStore } from '@/stores/auth/user'
import type { User } from '@/types/User'

interface RegisterData {
    username: string
    email: string
}

const USER_STORAGE_KEY = 'mirrorforest-user-store'
const REGISTER_STORAGE_KEY = 'mirrorforest-register-store'

export function clearAuthPersistence() {
  if (typeof window === 'undefined') return
  window.localStorage.removeItem(USER_STORAGE_KEY)
  window.localStorage.removeItem(REGISTER_STORAGE_KEY)
}

export const useRegisterStore = defineStore('register', {
  state: () => ({
    lastRegistered: null as RegisterData | null,
    lastRegisteredRaw: null as any,
  }),
  persist: {
    key: REGISTER_STORAGE_KEY,
    storage: window.localStorage,
    paths: ['lastRegistered', 'lastRegisteredRaw']
  } as any,
  actions: {
    async register(username: string, email: string, password: string, captchaId?: string, captchaCode?: string) {
      clearAuthPersistence()
      const res: ApiResponse<any> = await registerApi({ 
        username, 
        email, 
        password,
        captchaId,
        captchaCode
      })
      console.log('注册响应:', res)

      if (res.code === 0 || res.code === 200) {
        console.log('注册成功')
        // 持久化后端原始返回（例如完整用户对象或提示信息）
        this.lastRegisteredRaw = res.data ?? null
        // 同时保留可用于回显的基本信息
        const basic = res.data && typeof res.data === 'object'
          ? { username: (res.data.username ?? username), email: (res.data.email ?? email) }
          : { username, email }
        this.lastRegistered = basic

        // 如果后端直接返回了用户对象或令牌，则同步到对应的 store（将自动持久化）
        try {
          const userStore = useUserStore()
          const now = new Date().toISOString()
          const userPayload: Partial<User> = {
            id:res.data?.userId,
            username: res.data?.username ?? username,
            email: res.data?.email ?? email,
            display_name: res.data?.display_name ?? res.data?.displayName ?? null,
            avatar_url: res.data?.avatar_url ?? res.data?.avatarUrl ?? null,
            settings: res.data?.settings ?? null,
            is_active: typeof res.data?.is_active === 'boolean' ? res.data?.is_active : true,
            created_at: res.data?.created_at ?? now,
            updated_at: res.data?.updated_at ?? now
          }
          userStore.clearUser()
          userStore.setUser(userPayload)
          const access = (res as any).accessToken || (res.data && res.data.accessToken) || null
          const refresh = (res as any).refreshToken || (res.data && res.data.refreshToken) || null
        } catch (e) {
          console.warn('注册后同步用户/令牌到 store 时出现问题（可忽略）:', e)
        }
        return res
      } else {
        throw new Error(res.message || '注册失败')
      }
    }
  }
})
